﻿using CoreShop.App.Units.Interface;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.PrintService;
using CoreShop.Services;
using Loading;
using NPOI.SS.Formula.Functions;
using SqlSugar;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics.Eventing.Reader;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using Yitter.IdGenerator;

namespace CoreShop.App
{
    public partial class frmSetBalance : UIForm
    {
        private corecmsfoodorderingmaster orderingMaster = null;
        private List<corecmsfoodordering> orderingDetail = null;
        private List<corecmsfoodorderingtag> orderingTag = null;
        public corecmsuser member = null;
        public long orderId = 0;
        public string payCode = "";
        public int payType = -1;
        public int payTypeFirst = (int)GlobalEnumVars.Payment.cash;
        OpaqueCommand cmd = new OpaqueCommand();
        public frmSetBalance(corecmsuser _member, long _orderId, string _payCode = "", int _payType = -1)
        {
            InitializeComponent();
            dgvPayList.AutoGenerateColumns = false;
            this.member = _member;
            this.orderId = _orderId;
            this.payCode = _payCode;
            this.payType = _payType;
            numPad.FillColor = Color.White;
            txtSendKey.TextBox.GotFocus += txtSendKey_GotFocus;
        }

        private void txtSendKey_GotFocus(object sender, System.EventArgs e)
        {
            numPad.SetTextBox((UIEdit)sender, UITextBox.UIEditType.Double, 2);
        }

        private void frmSetBalance_Load(object sender, EventArgs e)
        {
            List<corecmsfoodorderpayment> lstPosPay = new List<corecmsfoodorderpayment>();
            this.binDetail.DataSource = lstPosPay;
            this.dgvPayList.DataSource = this.binDetail;            
            GetOrderingData(orderId);
            GetMemberInfo(false);
            LoadPaymentList();
        }

        private string GetItemName(int index)
        {
            return "btnPayment" + index.ToString();
        }

        /// <summary>
        /// 建支付按钮
        /// </summary>
        /// <param name="index"></param>
        private void CreatePaymentBtn(corecmspayments payInfo)
        {
            UISymbolButton btn = new UISymbolButton();            
            btn.Name = PaymentUtil.GetPayItemName(payInfo.id);
            btn.Size = payItemName.Size;
            btn.FillColor = payItemName.FillColor;
            btn.FillColor2 = payItemName.FillColor2;
            btn.Font = payItemName.Font;
            btn.ForeColor = payItemName.ForeColor;
            if (CommFunc.ConvertToInt32(payInfo.symbol) > 0)            
                btn.Symbol = CommFunc.ConvertToInt32(payInfo.symbol);
             else 
                btn.Symbol = 157471;
            btn.ForeSelectedColor = payItemName.ForeSelectedColor;
            btn.ImageAlign = payItemName.ImageAlign;
            btn.RectColor = payItemName.RectColor;
            btn.SymbolColor = payItemName.SymbolColor;
            btn.SymbolOffset = payItemName.SymbolOffset;
            btn.TextAlign = payItemName.TextAlign;
            btn.Padding = payItemName.Padding;
            btn.Text = payInfo.name;
            if (payInfo.id == (int)GlobalEnumVars.Payment.coupon)
                btn.Click += btnCoupon_Click;
            else 
                btn.Click += btnCash_Click;
            btn.Tag = payInfo.id;
            layPaymentList.Add(btn);            
        }

        private void LoadPaymentList()
        {
            if ((AppConstVars.sysPayments == null) || (AppConstVars.sysPayments.Count == 0))
                ProcessUtil.GetSystemPayment();//打开支付方式表

            var payList = AppConstVars.sysPayments.Where(p => p.isEnable == true && p.posUsed == 1).OrderBy(p=>p.sort).ToList();
            if (payList.Count == 0)
            {
                UIMessageBox.Show("没有选择支付方式。");
                this.Close();
            }
            else
            {
                //layPaymentList.Clear();
                if (payList.Count < 5)
                {
                    payItemName.Height = 76;
                    payItemName.SymbolOffset = new Point(0, 8);
                    payItemName.Padding = new Padding(0, 1, 0, 12);
                }
                if (payList.Count > 12)
                {
                    this.Width = 1230;
                    layPaymentList.Height = this.Height - layPaymentList.Top;
                    layPaymentList.Width = 250;
                    new DialogUtil().SetFormPosition(this);
                }
                else
                {
                    if (payList.Count > 8) this.Height = 638;
                    new DialogUtil().SetFormPosition(this);
                }

                foreach (var pay in payList)
                {
                    CreatePaymentBtn(pay);
                }

                if ((payType < 0) && (payList.Count > 0))
                {
                    var payItem = payList[0];
                    payTypeFirst = payItem.id;
                }
            }            
        }

        private void GetOrderingData(long orderId)
        {
            orderingMaster = new corecmsfoodorderingmasterServices().GetForUpdateOrderingMaster(orderId, AppConstVars.systemsetup.sumAmountDecimal);
            orderingDetail = new corecmsfoodorderingServices().QueryByOrderId(orderingMaster.orderId);
            orderingTag = new corecmsfoodorderingtagServices().QueryByOrderId(orderingMaster.orderId);
            if ((orderingMaster == null) || (orderingDetail == null) || (orderingDetail.Count == 0))
            {
                UIMessageBox.Show("没有可结算的数据。", "结算出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            }
            //满减活动计算
            decimal freeAmount = new ActivitieUtil().GetSpendingEnough(orderingMaster, member);
            //满折活动计算
            if (freeAmount == 0) freeAmount = new ActivitieUtil().GetFoldingActivity(orderingMaster, member);
            if (freeAmount > 0)
            {
                orderingMaster.sumFreeAmount = freeAmount;
                new OrderingUtil().SetOrderingFreeAmount(orderingMaster, freeAmount);
            }
            ShowTxtAmount();
        }

        public void ShowTxtAmount()
        {
            decimal dAllAmount = orderingMaster.sumAmount + orderingMaster.sumFeedAmount + orderingMaster.sumTaskAmount;
            lblAmount.Text = dAllAmount.ToString("0.0##");
            lblRealAmount.Text = orderingMaster.sumAllAmount.ToString("0.0##");
            lblDisAmount.Text = (dAllAmount - orderingMaster.sumAllAmount).ToString("0.0##");
            //txtSendKey.Text = orderingMaster.sumAllAmount.ToString("0.##");
        }

        /// <summary>
        /// 计算实付金额及找零售
        /// </summary>
        /// <param name="mPayID"></param>
        /// <param name="payAmount"></param>
        /// <param name="takeAmount"></param>
        /// <returns></returns>
        private decimal GetRealPayAmount(int mPayID, decimal takeAmount, bool isShowMsg, ref bool isComplete)
        {
            string msg;
            isComplete = false;
            lblChangeAmount.Text = "0.00";
            List<corecmsfoodorderpayment> posPays = this.binDetail.DataSource as List<corecmsfoodorderpayment>;

            decimal payedAmount = posPays.Select(p => p.payAmount).Sum();
            if ((payedAmount >= orderingMaster.sumAllAmount) && (orderingMaster.sumAllAmount != 0) && (takeAmount != 0))
            {
                msg = "支付金额已超过订单金额。如要继续，请删除支付明细表的数据。";
                if (isShowMsg) UIMessageBox.Show(msg, "支付出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                return 0;
            }

            if (mPayID == (int)GlobalEnumVars.Payment.cash)
            {
                decimal allTakeAmount = posPays.Where(p => p.paymentId == mPayID).Select(p => p.takeAmount).Sum();
                allTakeAmount += takeAmount;
                if (allTakeAmount - orderingMaster.sumAllAmount >= 100)
                {
                    msg = "支付的现金找零金额不能大于或等于100。如要继续，请删除支付明细表的数据。";
                    if (isShowMsg) UIMessageBox.Show(msg, "支付出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return 0;
                }

                decimal changAmount = allTakeAmount + payedAmount - orderingMaster.sumAllAmount;//找零金额
                if (changAmount > 0) lblChangeAmount.Text = changAmount.ToString("0.0#");

                if (allTakeAmount + payedAmount >= orderingMaster.sumAllAmount)
                {
                    //decimal allPayedAmount = posPays.Where(p => p.paymentId == mPayID).Select(p => p.payAmount).Sum();
                    isComplete = true;
                    return orderingMaster.sumAllAmount - payedAmount;
                }
                else
                {
                    return takeAmount;
                }
            }
            else if (mPayID == (int)GlobalEnumVars.Payment.coupon)
            {
                decimal allPayedAmount = posPays.Select(p => p.payAmount).Sum();
                if (allPayedAmount + takeAmount >= orderingMaster.sumAllAmount)
                {
                    isComplete = true;
                    return orderingMaster.sumAllAmount - allPayedAmount;
                }
                else
                {
                    return takeAmount;
                }
            }
            else
            {
                decimal allPayedAmount = posPays.Select(p => p.payAmount).Sum();
                if (allPayedAmount + takeAmount > orderingMaster.sumAllAmount)
                {
                    msg = "该支付方式不设找零，支付的数额不能大于订单金额。如要继续，请删除支付明细表的数据。";
                    if (isShowMsg)
                    {
                        UIMessageBox.Show(msg, "支付出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                        decimal unPayAmount = GetUnPayAmount();//未支付的金额
                        txtSendKey.Text = CommFunc.FormatDecimal(unPayAmount);
                    }
                    return 0;
                }
                if (allPayedAmount + takeAmount == orderingMaster.sumAllAmount) isComplete = true;
                //return orderingMaster.sumAllAmount - allPayedAmount;
                return takeAmount;
            }
        }


        /// <summary>
        /// 计算未支付的金额
        /// </summary>
        /// <returns></returns>
        private decimal GetUnPayAmount()
        {
            var orderPayment = this.binDetail.DataSource as List<corecmsfoodorderpayment>;
            decimal allPayAmount = orderPayment.Select(p => p.payAmount).Sum();
            return orderingMaster.sumAllAmount - allPayAmount;
        }


        /// <summary>
        /// 添加支付
        /// </summary>
        /// <param name="mPayID"></param>
        /// <param name="sPayCode">支付码</param>
        /// <param name="isComplete"></param>
        private void AddDataRow(int mPayID, string mPayCode, int mPayStatus, List<VipCouponInfoModel> payCoupons, ref bool isComplete)
        {
            decimal unPayAmount = GetUnPayAmount();//未支付的金额

            if ((string.IsNullOrEmpty(txtSendKey.Text)) && (unPayAmount != 0))
                txtSendKey.Text = CommFunc.FormatDecimal(unPayAmount);

            //已支付完
            if ((unPayAmount == 0) && (orderingMaster.sumAllAmount != 0))
            {
                isComplete = true;
                return;
            }

            decimal takeAmount = CommFunc.ConvertToDecimal(txtSendKey.Text);
            if (((string.IsNullOrEmpty(txtSendKey.Text)) || (takeAmount == 0)) && (orderingMaster.sumAllAmount != 0))
            {
                MessageBox.Show("没有输入支付金额。");
                txtSendKey.Focus();
                txtSendKey.SelectAll();
                return;
            }

            corecmspayments sysPayment = AppConstVars.sysPayments.Find(p => p.id == mPayID);
            if (sysPayment == null)
            {
                MessageBox.Show("支付信息不存在。");
                txtSendKey.Focus();
                txtSendKey.SelectAll();
                return;
            }
            decimal payAmount = GetRealPayAmount(mPayID, takeAmount, true, ref isComplete);
            if ((payAmount <= 0) && (orderingMaster.sumAllAmount != 0))
            {
                txtSendKey.Focus();
                txtSendKey.SelectAll();
                return;
            }
            var orderPayment = this.binDetail.DataSource as List<corecmsfoodorderpayment>;
            if ((mPayID == (int)GlobalEnumVars.Payment.alipay) || (mPayID == (int)GlobalEnumVars.Payment.alipay))
            {
                var orderpayment1 = orderPayment.Where(p => p.paymentId == (int)GlobalEnumVars.Payment.alipay
                || p.paymentId == (int)GlobalEnumVars.Payment.wechatpay).ToList();
                if (orderpayment1.Count > 0)
                {
                    UIMessageBox.Show("移动支付不能增加多行。", "支付出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
            }

            corecmsfoodorderpayment posPay = new corecmsfoodorderpayment();
            posPay.id = (long)YitIdHelper.NextId();//先给付值，方便删除行
            posPay.orderId = orderingMaster.orderId;
            posPay.orderNo = orderingMaster.orderNo;
            posPay.paymentId = sysPayment.id;
            posPay.payName = sysPayment.name;
            posPay.paymentCode = mPayCode;// sysPayment.code;
            posPay.payAmount = payAmount;
            posPay.takeAmount = takeAmount;
            posPay.status = mPayStatus;//先标记为未支付，如果移动支付等支付后改为已支付
            posPay.btnTitle = "删除";
            posPay.couponList = payCoupons;//优惠券支付列表
            posPay.outcomeType = (int)GlobalEnumVars.PayOutcomeType.Confirmed;
            this.binDetail.Add(posPay);
            this.binDetail.MoveLast();

            //LED顾显
            CustomerDisplay.SetLedShow(CommFunc.ConvertToDecimal(txtSendKey.Text).ToString("#0.00"), 2);

            if (!isComplete)
            {
                var btnSend = GetButtonByID((int)GlobalEnumVars.Payment.cash);
                btnCash_Click(btnSend, null);
                unPayAmount = GetUnPayAmount();//已支付完
                if (unPayAmount == 0)
                {
                    isComplete = true;
                    return;
                }
                txtSendKey.Text = GetUnPayAmount().ToString("0.##");
            }
            else txtSendKey.Text = "";

            txtSendKey.Focus();
            txtSendKey.SelectAll();
        }

        private UISymbolButton GetButtonByID(int payId)
        {
            var mControl = layPaymentList.Get(PaymentUtil.GetPayItemName(payId));
            var btnSend = (UISymbolButton)mControl;
            return btnSend;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            //bool check = CheckData1();
        }

        private void txtSendKey_TextChanged(object sender, EventArgs e)
        {
            txtSendKey.ShowButton = !string.IsNullOrEmpty(this.txtSendKey.Text);
            decimal takeAmount = CommFunc.ConvertToDecimal(txtSendKey.Text);
            int mPayID = CommFunc.ConvertToInt32(pnlPayName.Tag);
            bool isComplete = false;
            GetRealPayAmount(mPayID, takeAmount, false, ref isComplete);
        }

        private void dgvGoodsList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var orderPayment = this.binDetail.DataSource as List<corecmsfoodorderpayment>;
            int mRowIndex = e.RowIndex;
            if (dgvPayList.Columns[e.ColumnIndex].Name == "btnTitle")
            {
                Int64 payId = CommFunc.ConvertToInt64(dgvPayList.Rows[mRowIndex].Cells["id"].Value);
                var paymentModel = orderPayment.Find(p => p.id == payId);
                if (paymentModel != null)
                {
                    if (paymentModel.status == (int)GlobalEnumVars.OrderPayStatus.UnPay)
                    {
                        this.binDetail.DataSource = null;
                        orderPayment.Remove(paymentModel);
                        this.binDetail.DataSource = orderPayment;
                    }
                    else
                    {
                        string msg = "付款方式【" + paymentModel.payName + "】已支付完成，要删除吗？";
                        if (ShowAskDialog(msg))
                        {
                            this.binDetail.DataSource = null;
                            orderPayment.Remove(paymentModel);
                            this.binDetail.DataSource = orderPayment;
                        }
                    }
                    decimal unPayAmount = GetUnPayAmount();//未支付的金额
                    txtSendKey.Text = CommFunc.FormatDecimal(unPayAmount);
                    txtSendKey_TextChanged(this.txtSendKey, null);
                }
            }
        }

        private void btnCash_Click(object sender, EventArgs e)
        {
            try
            {
                if (sender == null) return;
                int mPayID = CommFunc.ConvertToInt32((sender as UISymbolButton).Tag);
                var payment = AppConstVars.sysPayments.Find(p => p.id == mPayID);
                if (payment == null)
                {
                    UIMessageBox.Show("没有找到该付款方式的信息。");
                    return;
                }
                if ((mPayID == (int)GlobalEnumVars.Payment.balancepay) && (member == null))
                {
                    UIMessageBox.Show("没有选择会员，不能选择储值支付。");
                    return;
                }
                foreach (var pay in AppConstVars.sysPayments) 
                {
                    var mControl = layPaymentList.Get(PaymentUtil.GetPayItemName(pay.id));
                    if (mControl != null)
                    {
                        var item = (UISymbolButton)mControl;
                        item.Selected = false;
                    }
                }
                UISymbolButton itemSelect = (UISymbolButton)sender;
                (sender as UISymbolButton).Selected = true;
                pnlPayName.Text = payment.name;
                pnlPayName.Tag = mPayID;
                if ((mPayID == (int)GlobalEnumVars.Payment.alipay) || (mPayID == (int)GlobalEnumVars.Payment.wechatpay)
                || (mPayID == (int)GlobalEnumVars.Payment.paymix) || (mPayID == (int)GlobalEnumVars.Payment.unionPay))
                {
                    string mPayStr = "请出示付款码";
                    SoundHelper.SetSpeechPayInfo(mPayStr);//播放声音;
                }
            }
            catch { }
            finally
            {
                txtSendKey.Focus();
                txtSendKey.SelectAll();
            }
        }


        private void GetMemberInfo(bool isSetOrderingData)
        {
            long oldMemberId = CommFunc.ConvertToInt64(btnGetMember.Tag);
            long newMemberId = 0;
            if (member != null) newMemberId = member.id;
            if ((oldMemberId != newMemberId) && (isSetOrderingData))
            {
                var bl = new MemberUtil().SetMemberData(orderingMaster.orderId, member);
                if (Program.frmCustShow != null) Program.frmCustShow.SetCustShowInfo(true);
            }
            btnGetMember.Tag = newMemberId.ToString();

            if (member != null)
            {
                btnGetMember.Text = "         " + member.nickName;
                lbl_MemberPhone.Text = member.mobile;
                lbl_MmbAmount.Text = member.balance.ToString("#0.00#");
                lbl_MemberPoint.Text = member.point.ToString();
                lbl_MemberTimes.Text = member.quantity.ToString();
            }
            else
            {
                btnGetMember.Text = "         选择会员";
                lbl_MemberPhone.Text = "";
                lbl_MmbAmount.Text = "0.00";
                lbl_MemberPoint.Text = "0";
                lbl_MemberTimes.Text = "0";
            }
        }

        private void txtSendKey_ButtonClick(object sender, EventArgs e)
        {
            txtSendKey.Text = "";
            txtSendKey.Focus();
        }

        private void btnGetMember_Click(object sender, EventArgs e)
        {
            var frm = new FrmUserGetInfo(member);
            frm.Owner = this;
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                member = frm.member;
                Program.frmOrdering.orderingMember = member;
                GetMemberInfo(true);
                Program.frmOrdering.GetMemberInfo(true);
                GetOrderingData(orderId);
                LoadDefaultPay();
            }
            frm.Dispose();
        }

        private void LoadDefaultPay()
        {
            txtSendKey.Text = GetUnPayAmount().ToString("0.##");
            if (!string.IsNullOrEmpty(payCode))
            {
                txtSendKey.Text = payCode;
                btnCash_Click(GetButtonByID((int)GlobalEnumVars.Payment.cash), null);
                numPad_OKButtonClick(nameof(txtSendKey_KeyPress), txtSendKey.Text, 0, 0);
            }
            else if (payType == (int)GlobalEnumVars.Payment.paymix)
            {
                txtSendKey.Text = this.lblRealAmount.Text;
                btnCash_Click(GetButtonByID((int)GlobalEnumVars.Payment.paymix), null);
                if ((AppConstVars.systemsetup.paraPartialModel.quickPayType == (int)GlobalEnumVars.QuickPayType.MobilePayment)
                    || (AppConstVars.systemsetup.paraPartialModel.quickPayType == (int)GlobalEnumVars.QuickPayType.AliPay_NFC))
                {
                    numPad_OKButtonClick(nameof(txtSendKey_KeyPress), txtSendKey.Text, 0, 0);
                }                    
            }
            else if (payType == (int)GlobalEnumVars.Payment.cash)
            {
                txtSendKey.Text = this.lblRealAmount.Text;
                btnCash_Click(GetButtonByID((int)GlobalEnumVars.Payment.cash), null);
                if (AppConstVars.systemsetup.paraPartialModel.quickPayType == (int)GlobalEnumVars.QuickPayType.CashQuickPay)
                    numPad_OKButtonClick(nameof(txtSendKey_KeyPress), txtSendKey.Text, 0, 0);
            }
            else if (member != null)
            {
                if (member.balance >= orderingMaster.sumAllAmount)
                {
                    btnCash_Click(GetButtonByID((int)GlobalEnumVars.Payment.balancepay), null);
                    return;
                }

                switch (AppConstVars.systemsetup.memberPayTip)
                {
                    case (int)GlobalEnumVars.MemberPayTip.TipToCash:
                        if (member.balance < orderingMaster.sumAllAmount)
                        {
                            UIMessageBox.Show("该储值卡的余额不足，将转现金支付。");
                            btnCash_Click(GetButtonByID((int)GlobalEnumVars.Payment.cash), null);          
                        }                            
                        break;
                    case (int)GlobalEnumVars.MemberPayTip.TipToMore:
                        if (member.balance == 0)
                        {
                            UIMessageBox.Show("该储值卡的余额为0，将转现金支付。");
                            btnCash_Click(GetButtonByID((int)GlobalEnumVars.Payment.cash), null);
                        }                            
                        else
                        {
                            string msg = "该存储卡余额是[" + member.balance.ToString("#0.00") + "],确定要组合支付本单吗？";
                            if (ShowAskDialog(msg))
                            {
                                btnCash_Click(GetButtonByID((int)GlobalEnumVars.Payment.balancepay), null);
                                txtSendKey.Text = member.balance.ToString("#0.##");
                            }
                        }
                        break;
                    case (int)GlobalEnumVars.MemberPayTip.ShowBalance:
                        btnCash_Click(GetButtonByID((int)GlobalEnumVars.Payment.balancepay), null);
                        txtSendKey.Text = member.balance.ToString("#0.##");
                        break;
                    case (int)GlobalEnumVars.MemberPayTip.ShowMemberPay:
                        btnCash_Click(GetButtonByID((int)GlobalEnumVars.Payment.balancepay), null);
                        break;
                    default:
                        btnCash_Click(GetButtonByID((int)GlobalEnumVars.Payment.cash), null);
                        break;
                }
            }
            else btnCash_Click(GetButtonByID(payTypeFirst), null);
        }

        private void frmSetBalance_Shown(object sender, EventArgs e)
        {
            LoadDefaultPay();
            txtSendKey.Focus();
            txtSendKey.SelectAll();
        }

        private void btnDiscount_Click(object sender, EventArgs e)
        {
            GetDiscountAmount(1);
        }

        private void GetDiscountAmount(int type)
        {
            var frm = new frmSetReduce(type);
            frm.orderingMaster = orderingMaster;
            frm.orderingTags = orderingTag;
            frm.Owner = this;
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                GetOrderingData(orderingMaster.orderId);
                ShowTxtAmount();
                decimal unPayAmount = GetUnPayAmount();//未支付的金额
                txtSendKey.Text = CommFunc.FormatDecimal(unPayAmount);
            }
            frm.Dispose();
            txtSendKey.Focus();
            txtSendKey.SelectAll();
        }

        private void btnSetReduceAmount_Click(object sender, EventArgs e)
        {
            GetDiscountAmount(2);
        }

        private void SetCouponPay(string code)
        {
            frmCouponPay fp = new frmCouponPay(orderingDetail, lblRealAmount.Text, code);
            fp.ShowDialog();
            if (fp.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                if (fp.mCouponPayAmt > 0)
                {
                    pnlPayName.Tag = "11";
                    pnlPayName.Text = "抖音券";
                    txtSendKey.Text = fp.mCouponPayAmt.ToString();
                    bool isComplete = false;
                    AddDataRow(11, "", (int)GlobalEnumVars.OrderPayStatus.UnPay, null, ref isComplete);
                }
            }
            fp.Dispose();
        }

        private VipPayParaDto GetMemberPayPara()
        {
            VipPayParaDto payParaDto = new VipPayParaDto();
            if (AppConstVars.syssetting.verifyPayPassword == 0) return payParaDto;
            var frm = new frmInputNumber(0, "会员消费密码");
            frm.IsNumber = false;
            frm.txtNumber.PasswordChar = '*';
            string password = "";
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                password = CommFunc.ConvertToString(frm.txtNumber.Text);
                if (string.IsNullOrEmpty(password))
                {
                    password = "123456";
                    payParaDto.checkPassword = 1;
                }
                else payParaDto.checkPassword = 0;
                payParaDto.password = password;
            } 
            else
            {
                payParaDto.checkPassword = 0;
                payParaDto.password = "";
            }
            frm.Dispose();
            if (!string.IsNullOrEmpty(password)) return payParaDto;
            return payParaDto;
        }

        private void RemovePayment(List<corecmsfoodorderpayment> orderpayments,corecmsfoodorderpayment orderpayment)
        {
            this.binDetail.DataSource = null;
            orderpayments.Remove(orderpayment);
            this.binDetail.DataSource = orderpayments;
        }

        /// <summary>
        /// 发起支付
        /// </summary>
        /// <returns></returns>
        private async Task<bool> SetPayment(corecmsfoodorderingmaster orderMaster, List<corecmsfoodorderpayment> orderpayments, string mPayCode)
        {
            if (orderpayments.Count == 0) return false;
            foreach (var payment in orderpayments)
            {
                payment.orderNo = orderMaster.orderNo;
            }

            #region 移动支付
            var mobilePay = orderpayments.Where(p => p.paymentId == (int)GlobalEnumVars.Payment.alipay
                || p.paymentId == (int)GlobalEnumVars.Payment.wechatpay 
                || p.paymentId == (int)GlobalEnumVars.Payment.paymix
                || p.paymentId == (int)GlobalEnumVars.Payment.unionPay).ToList();
            if (mobilePay.Count > 0)
            {
                if (mobilePay.Count > 1)
                {
                    UIMessageBox.Show("移动支付不能增加多行。", "支付出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                var orderpayment = mobilePay.First();
                orderpayment.payCode = mPayCode;                
                var bl = PaymentUtil.SetPaymentMobile(orderpayment);
                if (!bl)
                {
                    RemovePayment(orderpayments, orderpayment);
                    return false;
                }
                orderpayment.status = (int)GlobalEnumVars.OrderPayStatus.IsPay;
                SetSpeechPayInfo(orderpayment.payName, orderpayment.payAmount);//播放支付声音
            }
            #endregion

            #region 储值支付
            if ((member != null) && (member.id > 0))
            {
                orderingMaster.userOldBalance = member.balance;
                orderingMaster.userNewBalance = member.balance;
            }
            var memberPay = orderpayments.Where(p => p.paymentId == (int)GlobalEnumVars.Payment.balancepay).ToList();
            if (memberPay.Count > 0)
            {
                if (memberPay.Count > 1)
                {
                    UIMessageBox.Show("储值支付不能增加多行。", "支付出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
                if ((member != null) && (member.id > 0))
                {
                    var orderpayment = memberPay.First();
                    orderpayment.payCode = mPayCode;
                    
                    var payParaDto = GetMemberPayPara();
                    frmMemberPay frmPay = new frmMemberPay(orderingMaster, orderpayment, member, payParaDto);
                    if (frmPay.ShowDialog() != DialogResult.OK)
                    {
                        RemovePayment(orderpayments, orderpayment);
                        return false;
                    }                            
                    orderpayment.status = (int)GlobalEnumVars.OrderPayStatus.IsPay;
                }
                else
                {
                    UIMessageBox.Show("储值支付必须添加会员。", "支付出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                    var orderpayment = memberPay.First();
                    RemovePayment(orderpayments, orderpayment);
                    return false;
                }
            }                     
            #endregion

            #region 优惠券支付
            var couponuserList = PaymentUtil.GetCouponsFormPayments(orderpayments);
            if ((couponuserList != null) && (couponuserList.Count > 0))
            {
                var posRemoteServices = new PosRemoteServices(AppConstVars.sysUser.ccessToken);
                var bl = await MemberUtil.SetCouponList(orderingDetail, couponuserList, AppConstVars.sysUser,orderingMaster.sumAllAmount);
                if (!bl.status)
                {
                    UIMessageBox.Show(bl.msg);
                    return false;
                }
                foreach (var orderpayment in orderpayments)
                {
                    if (orderpayment.paymentId == (int)GlobalEnumVars.Payment.coupon)
                        orderpayment.status = (int)GlobalEnumVars.OrderPayStatus.IsPay;
                }
            }
            #endregion

            return true;
        }

        private void SetSpeechPayInfo(string mPayName, decimal mPayAmount)
        {
            //string mPayStr = mPayName + "支付" +  mPayAmount + "元";
            string mPayStr = mPayName + "支付" + CommonHelper.CmycurD(mPayAmount);
            //SoundHelper soundPay = new SoundHelper();
            SoundHelper.SetSpeechPayInfo(mPayStr);//播放声音
        }

        /// <summary>
        /// 获取班次信息
        /// </summary>
        private bool CheckClassData()
        {
            var classModel = new corecmsfoodorderclassServices().GetById(AppConstVars.classId);
            if (classModel == null)
            {
                UIMessageBox.Show("没有班次信息，不能结算。");
                return false;
            }
            if (AppConstVars.systemsetup.classOffTime <= 0) return true;
            TimeSpan timeDifference = DateTime.Now - classModel.starDate;
            if (timeDifference.Hours > AppConstVars.systemsetup.classOffTime)
            {
                string str = string.Format("超过限制时间未交班，不能结算。当前班次当班时间为：{0}", classModel.starDate.ToString("yyyy-MM-dd HH:ss:mm"));
                UIMessageBox.Show(str);
                return false;
            }
            return true;
        }

        private async void numPad_OKButtonClick(object sender, string text, int intvalue, double doublevalue)
        {
            try
            {
                cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                if (!CheckClassData()) return;

                int mPayId = CommFunc.ConvertToInt32(pnlPayName.Tag);
                bool isComplete = false;
                string mPayCode = "";//支付码
                string substring = "douyin";
                if (text.Contains(substring))
                {
                    SetCouponPay(text);
                    //txtSendKey.Clear();
                    //txtSendKey.Focus();
                    return;
                }

                //扫码支付
                if (text.Length > 15)
                {
                    bool isMobelePay = false;
                    int mMobilePayId = CommFunc.ConvertToInt32(pnlPayName.Tag);
                    mMobilePayId = new OrderingUtil().GetMobilePayType(text, ref isMobelePay, ref mMobilePayId);
                    if (isMobelePay)
                    {
                        mPayCode = text;
                        mPayId = mMobilePayId;
                        txtSendKey.Text = "";
                    }
                }

                AddDataRow(mPayId, "", (int)GlobalEnumVars.OrderPayStatus.UnPay, null, ref isComplete);

                if (!isComplete) return;

                if (string.IsNullOrEmpty(orderingMaster.orderNo))
                    orderingMaster.orderNo = ProcessUtil.GetOrderNo((int)GlobalEnumVars.SerialNumberType.零售单号);
                
                var orderPayments = this.binDetail.DataSource as List<corecmsfoodorderpayment>;                

                if (!await SetPayment(orderingMaster, orderPayments, mPayCode)) return;

                //顾显找零金额显示
                CustomerDisplay.SetLedShow(CommFunc.ConvertToDecimal(lblChangeAmount.Text).ToString("#0.00"), 4);

                #region 保存订单数据
                //if (((AppConstVars.systemsetup.billNumberTime == (int)GlobalEnumVars.BillNumberTime.Settlement)
                //    && (orderingMaster.payStatus == (int)GlobalEnumVars.OrderPayStatus.UnPay)) || (string.IsNullOrEmpty(orderingMaster.orderNo)))
                //    orderingMaster.orderNo = ProcessUtil.GetOrderNo((int)GlobalEnumVars.SerialNumberType.零售单号);

                corecmsfoodordermaster orderMaster = new corecmsfoodordermaster();
                var orderServices = new corecmsfoodordermasterServices();
                string resultStr = "";
                var bl = orderServices.SaveOrderData(AppConstVars.sysUser, orderingMaster, orderingDetail,
                    orderingTag, orderPayments, AppConstVars.classId, member, ref orderMaster, ref resultStr);

                if (!bl)
                {
                    UIMessageBox.Show(resultStr, "保存数据出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return;
                }
                #endregion

                //上传订单数据
                OrderApiUtil.SendOrderUp(AppConstVars.sysUser, AppConstVars.sysStore, AppConstVars.classNumber, orderingMaster.orderId);                
                if (AppConstVars.systemsetup.prinMethod == (int)GlobalEnumVars.PrinMethod.AutoPrin)
                {
                    new PrintServices().SetPrintOrdering(orderMaster);
                    new PrintServices().SetPrintSettlement(orderMaster);                    
                }
                if (AppConstVars.systemsetup.paraPartialModel.autoPrinLable == (int)GlobalEnumVars.PrinMethod.AutoPrin)
                    new PrintServices().SetPrintLabel(orderMaster);

                var mobilePay = orderPayments.Where(p => p.paymentId == (int)GlobalEnumVars.Payment.cash).ToList();
                if (mobilePay.Count > 0) CustomerDisplay.OpenCashbox();
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message, "结算出错:", UIStyle.Green, UIMessageBoxButtons.OK);
            }
            finally { cmd.HideOpaqueLayer(); }
        }

        private void txtSendKey_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                numPad_OKButtonClick(nameof(txtSendKey_KeyPress), txtSendKey.Text, 0, 0);
            } 
            else
            if (e.KeyChar == 12290)
            {
                string str = txtSendKey.Text;
                int idx = txtSendKey.SelectionStart;
                str = str.Insert(idx, ".");
                txtSendKey.Text = str;
                txtSendKey.SelectionStart = idx + 1;
                txtSendKey.Focus();
                e.Handled = true;
            }
        }

        private void btnCoupon_Click(object sender, EventArgs e)
        {
            if ((orderingMaster.userId == 0) || (member == null))
            {
                var btnSend = GetButtonByID((int)GlobalEnumVars.Payment.coupon);
                ShowInfoTip(btnSend, "没有选择会员，不能使用消费券。");
                return;
            }
            var mPayID = (int)GlobalEnumVars.Payment.coupon;
            List<VipCouponInfoModel> payCoupons = new List<VipCouponInfoModel>();
            var orderPayments = this.binDetail.DataSource as List<corecmsfoodorderpayment>;
            switch (AppConstVars.systemsetup.couponUsage)
            {
                case (int)GlobalEnumVars.CouponUsage.GetNumber:
                    var couponuser = PaymentUtil.GetCouponUsage(orderingDetail, member, orderPayments);
                    if (couponuser != null)
                    {
                        //待改
                        //pnlPayName.Text = EnumHelper.GetDescByValue<GlobalEnumVars.Payment>(mPayID);
                        //pnlPayName.Tag = mPayID.ToString();
                        //bool isComplete = false;
                        //decimal unPayAmount = GetUnPayAmount();//未支付的金额
                        //if (couponuser.parValue < unPayAmount) unPayAmount = couponuser.parValue.ObjToDecimal(0);
                        //txtSendKey.Text = unPayAmount.ToString();
                        //payCoupons.Add(couponuser);
                        //AddDataRow(mPayID, couponuser.id.ToString(), (int)GlobalEnumVars.OrderPayStatus.IsPay, payCoupons, ref isComplete);
                    }
                    else
                    {
                        //UIMessageBox.Show("核销优惠券失败，将转现金支付。");
                        var btnSend = GetButtonByID((int)GlobalEnumVars.Payment.cash);
                        btnCash_Click(btnSend, null);
                    }
                    break;
                case (int)GlobalEnumVars.CouponUsage.SelCoupon:
                    if (member == null)
                    {
                        UIMessageBox.Show("没有选择会员，不能", "结算出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                        return;
                    }
                    var couponuserList = PaymentUtil.GetCouponsFormPayments(orderPayments);
                    if ((couponuserList != null) && (couponuserList.Count > 0))
                    {
                        UIMessageBox.Show("每单只能选择一张优惠券。", "错误提示:", UIStyle.Green, UIMessageBoxButtons.OK);
                        return;
                    }
                    //选择后台的券
                    var payment = PaymentUtil.GetUserCouponPay(orderingDetail, member, orderingMaster);
                    if (payment != null)
                    {
                        pnlPayName.Text = EnumHelper.GetDescByValue<GlobalEnumVars.Payment>(mPayID);
                        pnlPayName.Tag = mPayID.ToString();
                        bool isComplete = false;
                        decimal unPayAmount = GetUnPayAmount();//未支付的金额
                        if (payment.payAmount < unPayAmount) unPayAmount = payment.payAmount;
                        txtSendKey.Text = unPayAmount.ToString();
                        payCoupons = payment.couponList;
                        AddDataRow(mPayID, payment.payCode, (int)GlobalEnumVars.OrderPayStatus.IsPay, payCoupons, ref isComplete);
                    }
                    else
                    {
                        var btnSend = GetButtonByID((int)GlobalEnumVars.Payment.cash);
                        btnCash_Click(btnSend, null);
                    }
                    break;
                default:
                    pnlPayName.Text = EnumHelper.GetDescByValue<GlobalEnumVars.Payment>(mPayID);
                    pnlPayName.Tag = mPayID.ToString();
                    break;
            }
        }

        private void frmSetBalance_FormClosed(object sender, FormClosedEventArgs e)
        {
            HideWaitForm();
        }
    }
}
